<template>
    <el-form label-width="150px">
        <el-form-item label="可选审计字段" class="checkbox-group-title">
            <el-checkbox-group v-model="selectedFields">
                <el-checkbox v-for="dict in availableFields" :key="dict.code" :value="dict.code" class="audit-checkbox">
                    <span>{{ dict.name }}</span>
                    <span>（{{ dict.type }}）</span>
                </el-checkbox>
            </el-checkbox-group>
        </el-form-item>
        <el-table ref="auditTable" :data="columns" row-key="id" :max-height="tableHeight">
            <el-table-column label="审计字段" prop="columnName" min-width="150" />
            <el-table-column label="描述" prop="description" min-width="200" />
            <el-table-column label="启用" min-width="100">
                <template #default="scope">
                    <el-switch v-model="scope.row.enable" @change="handleSwitchChange($event, scope.row)" />
                </template>
            </el-table-column>
            <el-table-column label="数据类型" prop="physicalType" min-width="120" />
        </el-table>
    </el-form>
</template>

<script setup>
import { ref, computed } from 'vue';

// 内置字典选项
const dictOptions = [
    { code: 'CreatedAt', name: '创建时间', type: 'datetime', dataType: 'DateTime?' },
    { code: 'CreatedBy', name: '创建人', type: 'bigint', dataType: 'long' },
    { code: 'UpdatedAt', name: '更新时间', type: 'datetime', dataType: 'DateTime?' },
    { code: 'UpdatedBy', name: '更新人', type: 'bigint', dataType: 'long' },
    { code: 'DeletedAt', name: '删除时间', type: 'datetime', dataType: 'DateTime?' },
    { code: 'DeletedBy', name: '删除人', type: 'bigint', dataType: 'long' }
];

const columns = defineModel({
    default: () => []
});

const { info } = defineProps({
    info: { type: Object, default: null }
});

// 将selectedFields改为计算属性实现双向绑定
const selectedFields = computed({
    get: () => columns.value.map(col => col.columnName),
    set: (newVal) => {
        const current = columns.value.map(col => col.columnName);
        // 添加新选项
        newVal.filter(code => !current.includes(code)).forEach(code => {
            const dict = dictOptions.find(d => d.code === code);
            columns.value.push({
                columnName: dict.code,
                enable: true,
                physicalType: dict.type,
                description: dict.name,
                fieldName: dict.code,
                dataType: dict.dataType
            });
        });
        columns.value = columns.value.filter(col => newVal.includes(col.columnName));
    }
});

const availableFields = computed(() =>
    dictOptions.map(dict => ({
        ...dict,
    }))
);

const tableHeight = ref(`${document.documentElement.scrollHeight - 245}px`);
const handleSwitchChange = (arg, row) => {
    row.enable = arg;
};
</script>

<style scoped>
.el-switch {
    margin-left: 8px;
}
</style>
